<?php

require_once 'q/dao.php';
require_once 'config/db.php';


class dao_admin_session extends q_dao {

    private $expire = 1800;

    private static $_instance = null;
    public static function getInstance(){
        if(!self::$_instance){
            self::$_instance = new dao_admin_session();
        }
        return self::$_instance;
    }

    public function get($session_key){
        $db = $this->_getdb(config_db::get('admin'));
        $sql = "select uid from admin_session "
            . " where session_key = '".$db->escape($session_key)."' "
            . "  and time_active > unix_timestamp() - " . $this->expire;
        $uid = $db->query_one($sql);

        if(!empty($uid)){
            $sql = "update admin_session "
                . " set time_active = unix_timestamp() "
                . " where session_key = '".$db->escape($session_key)."'";
            $db->query($sql);
        }

        return $uid;
    }

    public function set($session_key, $uid){
        $db = $this->_getdb(config_db::get('admin'));

        $this->delete($uid);
        $this->gc();

        $sql = "delete from admin_session "
            . " where session_key = '".$db->escape($session_key)."'";
        $db->query($sql);


        $sql = "insert into admin_session "
            . " (`session_key`,`uid`,`time_active`) "
            . " values "
            . " ('".$db->escape($session_key)."','".$db->escape($uid)."',unix_timestamp()) ";


        $db->query($sql);
    }

    public function delete($uid){
        $db = $this->_getdb(config_db::get('admin'));
        $sql = "delete from admin_session "
            . " where uid = '".$db->escape($uid)."' ";
        $db->query($sql);
    }

    public function gc(){
        $db = $this->_getdb(config_db::get('admin'));
        $sql = "delete from admin_session "
            . " where time_active < unix_timestamp() - " . $this->expire;
        $db->query($sql);
    }

}

